package org.ducinaltum.android.prima.services;

import java.util.HashMap;
import java.util.Random;

import org.ducinaltum.android.prima.services.DucInAltumService.Event;

public class EventRepositoryService {

	private static final int CACHE_SIZE = 50;

	private final HashMap<Long, Event> eventCache = new HashMap<Long, Event>();
	private final DucInAltumService service = new DucInAltumService();

	public synchronized Event getEventFromCache(final long id) {
		return eventCache.get(id);
	}

	public synchronized Event getEvent(final long id) throws ServiceException {
		Event event = getEventFromCache(id);
		if (event == null) {
			event = service.getEvent(id);
			addEventToCache(event);
		}
		return event;
	}

	private void addEventToCache(final Event event) {
		if (eventCache.size() >= CACHE_SIZE) {
			int randomIndex = new Random().nextInt(eventCache.size());
			Object key = eventCache.keySet().toArray()[randomIndex];
			eventCache.remove(key);
		}
		eventCache.put(event.id, event);
	}
}
